import 'package:flutter/material.dart';
import 'package:flutter/src/rendering/sliver.dart';
import 'package:flutter/src/rendering/sliver_grid.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    //脚手架
    return Scaffold(
      appBar: AppBar(
        title: Text('GridView'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      //girdview 用来实现宫格布局
      // body: ProductGrid(),
      body: PhotoWall(
        photoUrls: [
          'asset/images/b0.jpg',
          'asset/images/b02.webp',
          'asset/images/b03.png',
          'asset/images/b04.webp',
        ],
      ),
    );
  }

  GridView buildGridView4() {
    return GridView.custom(
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 150,
        mainAxisSpacing: 8.0,
        crossAxisSpacing: 8.0,
        childAspectRatio: 1.2,
      ),
      childrenDelegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          return Container(
            color: Colors.orange[100 * (index % 9)],
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.orange,
                    child: Text(
                      '${index + 1}',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  SizedBox(height: 4),
                  Text('Custom $index'),
                ],
              ),
            ),
          );
        },
        childCount: 25,
        addAutomaticKeepAlives: true, // 保持状态
        addRepaintBoundaries: true, // 添加重绘边界
      ),
    );
  }

  GridView buildGridView3() {
    return GridView.extent(
      maxCrossAxisExtent: 100, // 子项在交叉轴上的最大尺寸
      crossAxisSpacing: 12.0,
      mainAxisSpacing: 12.0,
      padding: EdgeInsets.all(16.0),
      children: List.generate(15, (index) {
        return Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.purple, Colors.pink],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(12.0),
            boxShadow: [
              BoxShadow(
                color: Colors.purple.withOpacity(0.3),
                blurRadius: 8.0,
                offset: Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.favorite, color: Colors.white, size: 32),
              SizedBox(height: 8),
              Text(
                'Item $index',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        );
      }),
    );
  }

  GridView buildGridView2() {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
        childAspectRatio: 1.0,
      ),
      itemCount: 100, // 总项目数
      itemBuilder: (BuildContext context, int index) {
        return Card(
          elevation: 4.0,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.star, size: 40, color: Colors.amber),
              SizedBox(height: 8),
              Text('Product $index'),
              Text(
                '\$${index * 10 + 5}',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ],
          ),
        );
      },
    );
  }

  GridView buildGridView1() {
    return GridView.count(
      // 网格配置
      crossAxisCount: 2, // 交叉轴上的项目数量（列数）
      crossAxisSpacing: 10.0, // 交叉轴间距
      mainAxisSpacing: 10.0, // 主轴间距
      padding: EdgeInsets.all(10.0), // 内边距
      childAspectRatio: 1.0, // 子项宽高比
      // 子项列表
      children: List.generate(20, (index) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.blue[100 * (index % 9)],
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Center(
            child: Text(
              'Item $index',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
        );
      }),
    );
  }
}

class ProductGrid extends StatefulWidget {
  @override
  _ProductGridState createState() => _ProductGridState();
}

class _ProductGridState extends State<ProductGrid> {
  final List<Product> products = [
    Product(name: '测试商品1', price: 999, image: 'asset/images/b03.png'),
    Product(name: '测试商品2', price: 699, image: 'asset/images/b04.webp'),
    Product(name: '测试商品1', price: 999, image: 'asset/images/b03.png'),
    Product(name: '测试商品2', price: 699, image: 'asset/images/b04.webp'),
    // ... 更多产品
  ];

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: const EdgeInsets.all(8.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: _calculateCrossAxisCount(context),
        crossAxisSpacing: 16.0,
        mainAxisSpacing: 16.0,
        childAspectRatio: 0.7,
      ),
      itemCount: products.length,
      itemBuilder: (context, index) {
        return ProductItem(product: products[index]);
      },
    );
  }

  int _calculateCrossAxisCount(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth > 300) return 4;
    if (screenWidth > 200) return 3;
    if (screenWidth > 100) return 2;
    return 1;
  }

  Widget ProductItem({required Product product}) {
    return Column(
      children: [
        Expanded(
          child: Image.asset(
            product.image,
            fit: BoxFit.fill,
            width: double.infinity,
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  product.name,
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
              ),
              Text(
                '￥${product.price}',
                style: TextStyle(fontSize: 16, color: Colors.red),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class Product {
  String name = '';
  int price = 0;
  String image = '';
  Product({required this.name, required this.price, required this.image});
}

class CustomGridDelegate extends SliverGridDelegate {
  final int maxCrossAxisCount;
  final double maxChildWidth;
  final double spacing;

  CustomGridDelegate({
    required this.maxCrossAxisCount,
    required this.maxChildWidth,
    this.spacing = 0.0,
  });

  @override
  bool shouldRelayout(covariant SliverGridDelegate oldDelegate) => true;

  @override
  SliverGridLayout getLayout(SliverConstraints constraints) {
    final crossAxisCount = (constraints.crossAxisExtent / maxChildWidth)
        .floor()
        .clamp(1, maxCrossAxisCount);
    final childWidth =
        (constraints.crossAxisExtent - spacing * (crossAxisCount - 1)) /
        crossAxisCount;

    return SliverGridRegularTileLayout(
      crossAxisCount: crossAxisCount,
      mainAxisStride: childWidth,
      crossAxisStride: childWidth,
      childMainAxisExtent: childWidth,
      reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
      childCrossAxisExtent: childWidth,
    );
  }
}

class PhotoWall extends StatelessWidget {
  final List<String> photoUrls;

  PhotoWall({required this.photoUrls});

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 2.0,
        mainAxisSpacing: 2.0,
      ),
      itemCount: photoUrls.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () => _showFullImage(context, index),
          child: Hero(
            tag: 'image_$index',
            child: Image.asset(photoUrls[index], fit: BoxFit.cover),
          ),
        );
      },
    );
  }

  void _showFullImage(BuildContext context, int index) {
    //显示大图
  }
}
